package com.os.osframe.scaffold.create;

import com.os.osframe.scaffold.domain.ScaffoldXmlField;
import com.os.osframe.scaffold.domain.ScaffoldXmlTable;
import com.os.osframe.scaffold.util.PropertyConfigurerLoader;
import com.os.osframe.util.StringUtil;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;

/**
 * Created by wangdc on 2015-4-27.
 */
public class CreateClassCode extends BaseCreate implements ICreateCode {

    public CreateClassCode(){

    }
    public CreateClassCode(ScaffoldXmlTable scaffoldXmlTable){
        super(scaffoldXmlTable);
    }
    public void create(String packages)throws Exception{
        System.out.println("=====开始生成类文件=====");
        String basePath = (String) getPropertyConfigurer().getProperty("osframe.file.path");//获取属性配置的服务器路径
        if (basePath.substring(basePath.length() - 1).equals("/")) {
            basePath = basePath.substring(basePath.length() - 1);
        }
        //String path = replaceStr(new File("").getAbsolutePath(), "\\", "/");//获取项目的根路径，这里获取到的是softdp的路径
        //System.out.println(path);//E:/java/intelijwork/softdp
        String targetFilePath=basePath;
        targetFilePath+="/auto/code/"+packages.replaceAll("\\.","/")+"/src";
        //System.out.println(targetFilePath);
        String tempPath = replaceStr(new File(this.getClass().getResource("").getPath()).getAbsolutePath(),"\\","/");//获取当前类所在路径
        if(tempPath.indexOf("create")>-1){
            tempPath=tempPath.substring(0,tempPath.length()-7);
        }
        tempPath+="/java";
        //System.out.println(tempPath);
        createFile(tempPath,targetFilePath);
    }
    /**
     * @param srcText
     * @return
     * @throws Exception
     */
    @Override
    protected String replaceCode(String srcText) throws Exception{
        if(scaffoldXmlTable==null ||scaffoldXmlTable.getStatus()==null || "false".equals(scaffoldXmlTable.getStatus())){
            return srcText;
        }
        srcText=replaceDomain(srcText,scaffoldXmlTable);

        return srcText;
    }

    /**
     * 替换模型页面
     * @param srcText
     * @param scaffoldXmlTable
     * @return
     * @throws Exception
     */
    protected String replaceDomain(String srcText,ScaffoldXmlTable scaffoldXmlTable) throws Exception{
        List<ScaffoldXmlField> scaffoldXmlFieldList =scaffoldXmlTable.getScaffoldXmlFieldList();
        StringBuffer sb=new StringBuffer();
        StringBuffer sbImport=new StringBuffer();
        StringBuffer sbForeign=new StringBuffer();//外键处理
        StringBuffer sbConvert=new StringBuffer();//数据类型处理 这里目前主要是manytomany
        /**
         * 数据源名称
         */
       /* @Column(name="lb_name",length = 200)
        protected String lbName;*/
        for(ScaffoldXmlField scaffoldXmlField : scaffoldXmlFieldList){
            //添加注释
            sb.append("\r\n").append("    ").append("/**");
            sb.append("\r\n").append("    ").append(" *"+ scaffoldXmlField.getFiledName());
            sb.append("\r\n").append("    ").append(" */");
            String simpleType= scaffoldXmlField.getJavaType();
            //XXX 暂时先不去支持list的域模型
            if(scaffoldXmlField.getJavaType()!=null && scaffoldXmlField.getJavaType().indexOf("com.os.osframe")>-1){//添加多对一
                sbImport.append("\r\n").append("import "+ scaffoldXmlField.getJavaType()+";");
                simpleType= scaffoldXmlField.getJavaType().substring(scaffoldXmlField.getJavaType().lastIndexOf(".")+1);

                if(scaffoldXmlField.getMapping()!=null && "manytomany".equals(scaffoldXmlField.getMapping().toLowerCase())){
                    String simpleType1= scaffoldXmlField.getJavaType().substring(scaffoldXmlField.getJavaType().lastIndexOf(".") + 1);
                    simpleType="List<"+simpleType+">";
                    sb.append("\r\n").append("    ").append("@ManyToMany(targetEntity="+scaffoldXmlField.getJavaType()+".class)");
                    if(StringUtil.isNotNull(scaffoldXmlField.getJoinTable())){
                        sb.append("\r\n").append("    ").append("@JoinTable(name=\""+scaffoldXmlField.getJoinTable()+"\"");
                    }else{// 默认生成级联表规则为，表名＋字段名（当字段名以lb_xxx_list这样的格式时，直接就可以取中间部分）
                        String filedMiddle=scaffoldXmlField.getFiledId();
                        if("lb_".equals(filedMiddle.substring(0, 3))){
                            filedMiddle=filedMiddle.substring(3);
                        }
                        if("_list".equals(filedMiddle.substring(filedMiddle.length()-5,filedMiddle.length()))){
                            filedMiddle=filedMiddle.substring(0, filedMiddle.length()-5);
                        }
                        sb.append("\r\n").append("    ").append("@JoinTable(name=\""+scaffoldXmlTable.getTableName()+"_"+filedMiddle+"\"");
                    }
                    if(StringUtil.isNotNull(scaffoldXmlField.getJoinSourceField())){
                        sb.append(", joinColumns = { @JoinColumn(name = \""+scaffoldXmlField.getJoinSourceField()+"\") }");
                    }else{
                        sb.append(", joinColumns = { @JoinColumn(name = \"lb_source_id\") }");
                    }
                    if(StringUtil.isNotNull(scaffoldXmlField.getJoinSourceField())){
                        sb.append(", inverseJoinColumns = { @JoinColumn(name = \""+scaffoldXmlField.getJoinTargetField()+"\") }");
                    }else{
                        sb.append(", inverseJoinColumns = { @JoinColumn(name = \"lb_target_id\") }");
                    }
                    sb.append(")");
                    sb.append("\r\n").append("    ").append("protected "+simpleType+" "+ scaffoldXmlField.getJavaFiledId()+";");
                    sbConvert.append("\r\n").append("    ").append("binder.registerCustomEditor(List.class,\""+scaffoldXmlField.getJavaFiledId()+"\", new ManyToManyListEditor("+simpleType1+".class));");
                    if(sbImport.toString().indexOf("ManyToManyListEditor")==-1){
                        sbImport.append("\r\n").append("import com.os.osframe.frame.convert.ManyToManyListEditor;");
                    }
                }else{
                    sb.append("\r\n").append("    ").append("@ManyToOne");
                    sb.append("\r\n").append("    ").append("@JoinColumn(name=\""+ scaffoldXmlField.getFiledId()+"\") ");
                    sb.append("\r\n").append("    ").append("protected "+simpleType+" "+ scaffoldXmlField.getJavaFiledId()+";");
                    sbForeign.append("\r\n").append("        ").append("if("+scaffoldXmlField.getJavaFiledId()+"!=null && StringUtil.isNull("+scaffoldXmlField.getJavaFiledId()+".getPkId())){");
                    sbForeign.append("\r\n").append("            ").append(scaffoldXmlField.getJavaFiledId()+"=null;");
                    sbForeign.append("\r\n").append("        ").append("}");
                    if(sbImport.toString().indexOf("StringUtil")==-1){
                        sbImport.append("\r\n").append("import com.os.osframe.util.StringUtil;");
                    }

                }

            }else{
                if(scaffoldXmlField.getFiledType()!=null && ( "clob".equals(scaffoldXmlField.getFiledType().toLowerCase()) ||  "blob".equals(scaffoldXmlField.getFiledType().toLowerCase()))){
                    sb.append("\r\n").append("    ").append("@Lob");
                    if("blob".equals(scaffoldXmlField.getFiledType().toLowerCase()) ){
                        sb.append("\r\n").append("    ").append("@Type(type=\"org.hibernate.type.MaterializedBlobType\")");
                    }else{
                        sb.append("\r\n").append("    ").append("@Type(type=\"org.hibernate.type.MaterializedClobType\")");
                    }
                    sb.append("\r\n").append("    ").append("@Basic(fetch=FetchType.LAZY)");
                }
                sb.append("\r\n").append("    ").append("@Column(name=\"" + scaffoldXmlField.getFiledId()+"\"");
                if(scaffoldXmlField.getFiledLength()!=null && !"".equals(scaffoldXmlField.getFiledLength())){//避免当length为空时导致报错
                    sb.append(",length = "+ scaffoldXmlField.getFiledLength());
                }
                sb.append(")");
                sb.append("\r\n").append("    ").append("protected "+ scaffoldXmlField.getJavaType()+" "+ scaffoldXmlField.getJavaFiledId()+";");
            }
            //添加get set方法
            sb.append("\r\n").append("    ").append("public "+simpleType+" get"+ scaffoldXmlField.getJavaFiledId().substring(0,1).toUpperCase()+ scaffoldXmlField.getJavaFiledId().substring(1)+"() {");
            sb.append("\r\n").append("        ").append("return "+ scaffoldXmlField.getJavaFiledId()+";");
            sb.append("\r\n").append("    ").append("}");
            sb.append("\r\n").append("    ").append("public void set"+ scaffoldXmlField.getJavaFiledId().substring(0,1).toUpperCase()+ scaffoldXmlField.getJavaFiledId().substring(1)+"("+simpleType+" "+ scaffoldXmlField.getJavaFiledId()+") {");
            sb.append("\r\n").append("        ").append("this."+ scaffoldXmlField.getJavaFiledId()+" = "+ scaffoldXmlField.getJavaFiledId()+";");
            sb.append("\r\n").append("    ").append("}");
            //当为manytomany时，直接添加获取id和name字符串的
            if(scaffoldXmlField.getMapping()!=null && "manytomany".equals(scaffoldXmlField.getMapping().toLowerCase())){
                sb.append("\r\n").append("    ").append("public String get"+scaffoldXmlField.getJavaFiledId().substring(0,1).toUpperCase()+ scaffoldXmlField.getJavaFiledId().substring(1)+"Ids() {");
                sb.append("\r\n").append("        ").append("return EntityUtil.getEntityFieldList(this."+scaffoldXmlField.getJavaFiledId()+",\""+scaffoldXmlField.getForeignId()+"\");");
                sb.append("\r\n").append("    ").append("}");
                sb.append("\r\n").append("    ").append("public String get"+scaffoldXmlField.getJavaFiledId().substring(0,1).toUpperCase()+ scaffoldXmlField.getJavaFiledId().substring(1)+"Names() {");
                sb.append("\r\n").append("        ").append("return EntityUtil.getEntityFieldList(this."+scaffoldXmlField.getJavaFiledId()+",\""+scaffoldXmlField.getForeignName()+"\");");
                sb.append("\r\n").append("    ").append("}");
                if(sbImport.toString().indexOf("EntityUtil")==-1){
                    sbImport.append("\r\n").append("import com.os.osframe.util.EntityUtil;");
                }
            }
        }
        if(sbForeign!=null && StringUtil.isNotNull(sbForeign.toString())){//新增的预处理，避免为空的对象无法保存的问题
            sb.append("\r\n").append("    ").append("@Override");
            sb.append("\r\n").append("    ").append("public void domainSetFields(){");
            sb.append("\r\n").append("    ").append(sbForeign.toString());
            sb.append("\r\n").append("    ").append("}");
        }
        if(sbConvert!=null && StringUtil.isNotNull(sbConvert.toString())){
            sb.append("\r\n").append("    ").append("@Override");
            sb.append("\r\n").append("    ").append("public void convertFields(HttpServletRequest request, ServletRequestDataBinder binder) {");
            sb.append("\r\n").append("       ").append("super.convertFields( request,  binder);");
            sb.append("\r\n").append("    ").append(sbConvert.toString());
            sb.append("\r\n").append("    ").append("}");
            sbImport.append("\r\n").append("import javax.servlet.http.HttpServletRequest;");
            sbImport.append("\r\n").append("import org.springframework.web.bind.ServletRequestDataBinder;");
        }
        srcText=replaceStr(srcText,"${domainImportCode}",sbImport.toString());
        srcText=replaceStr(srcText,"${domainCode}",sb.toString());
        return srcText;
    }

}
